﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;

namespace DevCore.Refection
{
    /// <summary>
    /// 反射辅助类
    /// </summary>
    public class RefectionHelper
    {
        /// <summary>
        /// 从行数据中。将行的属性填充至实体中。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="dt"></param>
        public static void SetEntityInfo<T>(T entity, DataTable dt)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                Type type = typeof(T);
                PropertyInfo[] propertyInfos = type.GetProperties();
                DataRow dr = dt.Rows[0];
                T t = Activator.CreateInstance<T>();
                for (int i = 0; i < propertyInfos.Length; i++)
                {
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (dt.Columns[j].ColumnName.ToLower() == propertyInfos[i].Name.ToLower())
                        {
                            if (dr[propertyInfos[i].Name] != DBNull.Value)
                            {
                                propertyInfos[i].SetValue(entity, dr[propertyInfos[i].Name], null);
                            }
                            break;
                        }
                    }


                }
            }
        }
    }
}
